import React, { useEffect, useState } from 'react';
import { Button, Table, Space, Switch, Breadcrumb, Modal, message, Form, Checkbox, Input} from 'antd';
import { DatabaseOutlined } from '@ant-design/icons';
import axios from 'axios';
import { getMenuList, getMenuById, deleteMenu } from '../../service/menu';
import { useParams } from 'react-router-dom';
const { confirm } = Modal;

const Menus = () => {

    const [menuData, setMenuData] = useState([]);
    const [expandedRowData, setExpandedRowData] = useState({});

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalContent, setModalContent] = useState('');
    const [modalTitle, setModalTitle] = useState('');

    const { id } = useParams();
    const [form] = Form.useForm();

    //发送接口获取数据/menu/list
    useEffect(() => {
        fetchMenuList();
      }, []);
  
    const fetchMenuList = () => {
        getMenuList().then((response) => {
          console.log(response.data);
          setMenuData(response.data.menuData);
          setExpandedRowData(response.data.expandedRowData);
        });
    };

    // 实现编辑
    const showModal = (id) => {
        setModalTitle('编辑');

        getMenuById(id).then((response) => {
            const { code, result } = response.data;
            if (code === 1 && result) {
              const data = { ...result};
              setMenuData(data);
              console.log(data);
              form.setFieldsValue(data);
            }
        });

        setModalContent(
            <Form form={form}>
              <Form.Item name="name" label="姓名">
                <Input />
              </Form.Item>
              <Form.Item name="description" label="描述">
                <Input />
              </Form.Item>
              <Form.Item name="userNum" label="用户数">
                <Input />
              </Form.Item>
              <Form.Item name="createTime" label="创建时间">
                <Input />
              </Form.Item>
              <Form.Item name="ifused" label="是否启用" valuePropName="checked">
                <Checkbox />
              </Form.Item>
            </Form>
        );
        setIsModalOpen(true);
    }

    const handleOk = async () => {
        setIsModalOpen(false);
    };
  
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 实现删除
    const handleDelete = (id) => {
        confirm({
          title: '确认删除吗',
          okText: '确认',
          cancelText: '取消',
          onOk(){
            return deleteMenu(id).then((response) => {
              const { code, msg } = response.data;
              if (code === 1) {
                message.success(msg);
                fetchMenuList();
              }
            });
          },
        });
      };

    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '菜单名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '菜单级数',
            dataIndex: 'level',
            key: 'level',
        },
        {
            title: '前端名称',
            dataIndex: 'nameshow',
            key: 'nameshow',
        },
        {
            title: '前端图标',
            dataIndex: 'showicon',
            key: 'showicon',
        },
        {
            title: '是否显示',
            dataIndex: 'ifshow',
            key: 'ifshow',
            render: (text, record) => (
                <Switch checked={record.ifshow}
                    onChange={(checked) => handleSwitchChange(record, checked)}
                    style={{ width: '40px' }} />
            ),
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
        },
        {
            title: '操作',
            key: 'operation',
            render: (text, record) => (
                <Space size="">
                    <Button type='link' style={{width: '50px'}} onClick={() => showModal(record.id)}>编辑</Button>
                    <Button type='link' style={{width: '50px'}} onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            ),
        },
    ];

    const expandedRowRender = (record) => {
        const data = expandedRowData[record.key] || [];
        const isParentDisabled = !record.ifshow;
        return (
            <Table
                columns={columns.map(col => {
                    if (col.dataIndex === 'ifshow') {
                        return {
                            ...col,
                            render: (text, childRecord) => (
                                <Switch checked={childRecord.ifshow}
                                    onChange={(checked) => handleSwitchChange(childRecord, checked, record.key)}
                                    style={{ width: '40px' }}
                                    disabled={isParentDisabled}
                                />
                            )
                        };
                    }
                    return col;
                })}
                dataSource={data}
                pagination={false}
            />
        );
    };

    // 修改switch
    const handleSwitchChange = (record, checked, parentKey = null) => {
        console.log('Switch changed:', record.id, checked);
    
        const updateData = (data, isParent = false) => {
            return data.map(item => {
                if (item.id === record.id) {
                    const updatedItem = { ...item, ifshow: checked };
                    if (isParent && !checked && expandedRowData[record.key]) {
                        expandedRowData[record.key].forEach(child => {
                            child.ifshow = false;
                        });
                    }
                    return updatedItem;
                }
                if (item.children) {
                    return { ...item, children: updateData(item.children) };
                }
                return item;
            });
        };
    
        if (parentKey === null) {
            // Update main menuData
            const newData = updateData(menuData, true);
            setMenuData(newData);
        } else {
            // Update expandedRowData
            const newExpandedData = {
                ...expandedRowData,
                [parentKey]: updateData(expandedRowData[parentKey])
            };
            setExpandedRowData(newExpandedData);
        }
    };
    
    return (
        <div className='datalist-container'>
            <Breadcrumb
              style={{
                margin: '16px 0',
              }}
            >
              <Breadcrumb.Item>权限</Breadcrumb.Item>
              <Breadcrumb.Item>菜单</Breadcrumb.Item>
            </Breadcrumb>
            <div className='datalist-header'
                style={{
                    width: '100%',
                    height: '50px',
                    display: 'flex',
                    border: '1px solid #ccc',
                    borderRadius: '5px'
                }}>
                <DatabaseOutlined style={{ marginLeft: '8px' }} /> 
                <span style={{ 
                        flex: 1, 
                        marginLeft: '10px',
                        fontSize: '16px',
                        marginTop: '12px'
                        }}>
                    数据列表
                </span> 
                <Button htmlType='submit' 
                        style={{ 
                            width: '80px',
                            height: '30px',
                            marginRight: '20px',
                            marginTop: '10px' 
                        }}>
                    添加
                </Button>
            </div>
            <div className='datalist-body'>
                <Table
                    columns={columns}
                    expandable={{
                    expandedRowRender,
                    defaultExpandedRowKeys: ['0'],
                    }}
                    dataSource={menuData}
                    style={{ marginTop: '20px'}}
                />
            </div>
        </div>
    )
};

export default Menus;